package com.cuit.mimall.controller.frontend;

import com.cuit.mimall.common.R;
import com.cuit.mimall.entity.User;
import com.cuit.mimall.mapper.UserMapper;
import com.cuit.mimall.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

/**
 * @author : TeaWu
 * @folder 前台/用户
 */
@RestController("frontendUserController")
@RequestMapping("/api/v1/frontend/user")
public class UserController {
    private final IUserService userService;

    @Autowired
    public UserController(IUserService userService) {
        this.userService = userService;
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/info")
    public R<?> info() {
        return userService.info();
    }

    //用户修改密码
    @PutMapping("/{userId}/password")
    public R<?> updatePasswordByUserId(@PathVariable Long userId,
                                       @RequestParam String oldPassword,
                                       @RequestParam String newPassword,
                                       @RequestParam String confirmPassword){
        boolean success= userService.updatePasswordByUserId(userId,oldPassword,newPassword,confirmPassword);
        if(success){
            return R.ok("密码修改成功");
        }else {
            return R.ok("密码修改失败");
        }
    }

    //用户进行头像上传
    @Autowired
    private UserMapper userMapper;
    @PostMapping("/{userId}/avatar")
    public R<?> uploadAvatar(@PathVariable Long userId, @RequestParam("file") MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            String filePath = "D:/FileUpload/" + fileName; // 设置保存路径

            // 保存文件到指定路径
            File dest = new File(filePath);
            file.transferTo(dest);

            // 更新用户实体的头像字段
            User user = userMapper.selectById(userId);
            user.setAvatar(filePath);
            userMapper.updateById(user);

            return R.ok("Avatar uploaded successfully");
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("Avatar uploaded failed");
        }
    }


    @PutMapping("/{userId}/updataInfo")
    public R<?> updateUserInformation(
            @PathVariable Long userId,
            @RequestParam String nickName,
            @RequestParam String email,
            @RequestParam String phoneNumber) {

        boolean success= userService.updateUserInformation(userId,nickName,email,phoneNumber);
        if(success){
            return R.ok("修改成功");
        }else {
            return R.ok("修改失败");
        }
    }
}

